package com.ibm.iisp.common.dao;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.iisp.common.util.JacksonObjectMapperFactory;

/**
 * 
 * 转换通用的多属性字段到数据库单个VARCHAR字段
 * 
 * @author JohnnyZhou
 *
 */
@Converter
public class MapJsonConverter implements AttributeConverter<Map<String, ?>, String> {

	ObjectMapper objectMapper = JacksonObjectMapperFactory.getObjectMapper();

	@Override
	public String convertToDatabaseColumn(Map<String, ?> val) {
		if (val == null) {
			return null;
		}
		try {
			return objectMapper.writeValueAsString(val);
		} catch (Exception ex) {
			throw new RuntimeException("JSON 转换出错:" + val, ex);
		}
	}

	@Override
	public Map<String, ?> convertToEntityAttribute(String dbData) {
		if (dbData == null) {
			return null;
		}
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> val = objectMapper.readValue(dbData, Map.class);
			for (Map.Entry<String, Object> entry: val.entrySet()) {
				String key = entry.getKey();
				if (key.endsWith("Date") || key.endsWith("Time") || key.endsWith("Timestamp")) {
					Object _val = entry.getValue();
					if (_val instanceof Long) {
						entry.setValue(new Date((Long)_val));
					}
				}
			}
			return val;
		} catch (IOException ex) {
			throw new RuntimeException("JSON 转换出错:" + dbData, ex);
		}
	}

}
